<template>
    <div class="variable-management">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>变量管理</span>
                    <el-button type="primary" @click="showAddDialog = true">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        添加变量
                    </el-button>
                </div>
            </template>

            <!-- 搜索区域 -->
            <div class="search-area">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-input 
                            v-model="searchForm.search" 
                            placeholder="搜索变量名称、键名或描述" 
                            @keyup.enter="handleSearch"
                            clearable
                        >
                            <template #append>
                                <el-button @click="handleSearch">
                                    <el-icon>
                                        <Search />
                                    </el-icon>
                                </el-button>
                            </template>
                        </el-input>
                    </el-col>
                    <el-col :span="4">
                        <el-select 
                            v-model="searchForm.category" 
                            placeholder="选择分类" 
                            clearable
                            @change="handleSearch"
                        >
                            <el-option 
                                v-for="category in categories" 
                                :key="category.key" 
                                :label="category.name" 
                                :value="category.key" 
                            />
                        </el-select>
                    </el-col>
                    <el-col :span="4">
                        <el-button @click="resetSearch">重置</el-button>
                    </el-col>
                </el-row>
            </div>

            <!-- 变量表格 -->
            <el-table 
                v-loading="loading" 
                :data="variables" 
                style="width: 100%" 
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" />
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="name" label="变量名称" min-width="120" />
                <el-table-column prop="key" label="变量键名" min-width="120" />
                <el-table-column prop="value" label="变量值" min-width="150" show-overflow-tooltip />
                <el-table-column prop="category" label="分类" width="120">
                    <template #default="{ row }">
                        <el-tag :type="getCategoryTagType(row.category)">
                            {{ getCategoryName(row.category) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip />
                <el-table-column prop="is_active" label="状态" width="80">
                    <template #default="{ row }">
                        <el-tag :type="row.is_active ? 'success' : 'danger'">
                            {{ row.is_active ? '启用' : '禁用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="updated_at" label="更新时间" width="150" />
                <el-table-column label="操作" width="180" fixed="right">
                    <template #default="{ row }">
                        <el-button size="small" @click="editVariable(row)">编辑</el-button>
                        <el-button size="small" type="danger" @click="deleteVariable(row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 批量操作 -->
            <div v-if="selectedVariables.length > 0" class="batch-actions">
                <el-alert 
                    :title="`已选择 ${selectedVariables.length} 项`" 
                    type="info" 
                    show-icon 
                    :closable="false"
                >
                    <template #default>
                        <el-button size="small" type="danger" @click="batchDelete">
                            批量删除
                        </el-button>
                    </template>
                </el-alert>
            </div>

            <!-- 分页 -->
            <div class="pagination">
                <el-pagination 
                    v-model:current-page="pagination.page" 
                    v-model:page-size="pagination.per_page"
                    :page-sizes="[10, 20, 50, 100]" 
                    :total="pagination.total"
                    layout="total, sizes, prev, pager, next, jumper" 
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" 
                />
            </div>
        </el-card>

        <!-- 添加/编辑变量对话框 -->
        <el-dialog 
            v-model="showAddDialog" 
            :title="editingVariable ? '编辑变量' : '添加变量'" 
            width="600px" 
            @closed="resetForm"
        >
            <el-form 
                ref="variableFormRef" 
                :model="variableForm" 
                :rules="variableRules" 
                label-width="100px"
            >
                <el-form-item label="变量名称" prop="name">
                    <el-input v-model="variableForm.name" placeholder="请输入变量名称" />
                </el-form-item>

                <el-form-item label="变量键名" prop="key">
                    <el-input 
                        v-model="variableForm.key" 
                        placeholder="请输入变量键名（唯一标识）"
                        :disabled="!!editingVariable"
                    />
                    <div class="form-tip">键名用于程序中引用变量，创建后不可修改</div>
                </el-form-item>

                <el-form-item label="变量分类" prop="category">
                    <el-select v-model="variableForm.category" placeholder="请选择变量分类">
                        <el-option 
                            v-for="category in categories" 
                            :key="category.key" 
                            :label="category.name" 
                            :value="category.key" 
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="变量值" prop="value">
                    <el-input 
                        v-model="variableForm.value" 
                        type="textarea" 
                        :rows="3"
                        placeholder="请输入变量值"
                    />
                </el-form-item>

                <el-form-item label="变量描述" prop="description">
                    <el-input 
                        v-model="variableForm.description" 
                        type="textarea" 
                        :rows="2"
                        placeholder="请输入变量描述（可选）"
                    />
                </el-form-item>

                <el-form-item label="启用状态" prop="is_active">
                    <el-switch v-model="variableForm.is_active" />
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showAddDialog = false">取消</el-button>
                    <el-button type="primary" :loading="submitLoading" @click="submitVariable">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const loading = ref(false)
const submitLoading = ref(false)
const showAddDialog = ref(false)
const editingVariable = ref(null)
const selectedVariables = ref([])

const variables = ref([])
const categories = ref([])

const searchForm = reactive({
    search: '',
    category: ''
})

const pagination = reactive({
    page: 1,
    per_page: 10,
    total: 0,
    pages: 0
})

const variableForm = reactive({
    name: '',
    key: '',
    value: '',
    category: '',
    description: '',
    is_active: true
})

const variableFormRef = ref()

const variableRules = {
    name: [
        { required: true, message: '请输入变量名称', trigger: 'blur' },
        { min: 1, max: 100, message: '变量名称长度在 1 到 100 个字符', trigger: 'blur' }
    ],
    key: [
        { required: true, message: '请输入变量键名', trigger: 'blur' },
        { min: 1, max: 100, message: '变量键名长度在 1 到 100 个字符', trigger: 'blur' },
        { 
            pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/, 
            message: '变量键名只能包含字母、数字和下划线，且不能以数字开头', 
            trigger: 'blur' 
        }
    ],
    value: [
        { required: true, message: '请输入变量值', trigger: 'blur' }
    ],
    category: [
        { required: true, message: '请选择变量分类', trigger: 'change' }
    ]
}

// 获取分类名称
const getCategoryName = (categoryKey) => {
    const category = categories.value.find(c => c.key === categoryKey)
    return category ? category.name : categoryKey
}

// 获取分类标签类型
const getCategoryTagType = (categoryKey) => {
    const typeMap = {
        'product': 'primary',
        'system': 'success',
        'workshop': 'warning'
    }
    return typeMap[categoryKey] || 'info'
}

// 获取变量分类列表
const fetchCategories = async () => {
    try {
        const response = await axios.get('/api/variables/categories')
        categories.value = response.data.categories
    } catch (error) {
        ElMessage.error('获取变量分类失败: ' + (error.response?.data?.message || error.message))
    }
}

// 获取变量列表
const fetchVariables = async () => {
    loading.value = true
    try {
        const params = {
            page: pagination.page,
            per_page: pagination.per_page,
            search: searchForm.search,
            category: searchForm.category
        }

        const response = await axios.get('/api/variables', { params })
        variables.value = response.data.variables
        pagination.total = response.data.total
        pagination.pages = response.data.pages
    } catch (error) {
        ElMessage.error('获取变量列表失败: ' + (error.response?.data?.message || error.message))
    } finally {
        loading.value = false
    }
}

// 搜索
const handleSearch = () => {
    pagination.page = 1
    fetchVariables()
}

// 重置搜索
const resetSearch = () => {
    searchForm.search = ''
    searchForm.category = ''
    pagination.page = 1
    fetchVariables()
}

// 分页
const handleSizeChange = (val) => {
    pagination.per_page = val
    pagination.page = 1
    fetchVariables()
}

const handleCurrentChange = (val) => {
    pagination.page = val
    fetchVariables()
}

// 选择变化
const handleSelectionChange = (val) => {
    selectedVariables.value = val
}

// 编辑变量
const editVariable = (variable) => {
    editingVariable.value = variable
    variableForm.name = variable.name
    variableForm.key = variable.key
    variableForm.value = variable.value
    variableForm.category = variable.category
    variableForm.description = variable.description || ''
    variableForm.is_active = variable.is_active
    showAddDialog.value = true
}

// 删除变量
const deleteVariable = async (variable) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除变量 "${variable.name}" 吗？`,
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        await axios.delete(`/api/variables/${variable.id}`)
        ElMessage.success('删除成功')
        fetchVariables()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message))
        }
    }
}

// 批量删除
const batchDelete = async () => {
    try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${selectedVariables.value.length} 个变量吗？`,
            '批量删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        const ids = selectedVariables.value.map(v => v.id)
        await axios.delete('/api/variables/batch', { data: { ids } })
        ElMessage.success('批量删除成功')
        fetchVariables()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('批量删除失败: ' + (error.response?.data?.message || error.message))
        }
    }
}

// 提交变量表单
const submitVariable = async () => {
    if (!variableFormRef.value) return

    await variableFormRef.value.validate(async (valid) => {
        if (valid) {
            submitLoading.value = true
            try {
                const data = { ...variableForm }

                if (editingVariable.value) {
                    await axios.put(`/api/variables/${editingVariable.value.id}`, data)
                    ElMessage.success('更新成功')
                } else {
                    await axios.post('/api/variables', data)
                    ElMessage.success('创建成功')
                }

                showAddDialog.value = false
                fetchVariables()
            } catch (error) {
                ElMessage.error((editingVariable.value ? '更新' : '创建') + '失败: ' + (error.response?.data?.message || error.message))
            } finally {
                submitLoading.value = false
            }
        }
    })
}

// 重置表单
const resetForm = () => {
    editingVariable.value = null
    variableForm.name = ''
    variableForm.key = ''
    variableForm.value = ''
    variableForm.category = ''
    variableForm.description = ''
    variableForm.is_active = true
    variableFormRef.value?.resetFields()
}

onMounted(() => {
    fetchCategories()
    fetchVariables()
})
</script>

<style scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-area {
    margin-bottom: 20px;
}

.batch-actions {
    margin: 20px 0;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}

.form-tip {
    font-size: 12px;
    color: #999;
    margin-top: 4px;
}
</style>